import { getAuthorize } from '@/api/api'
import { setToken } from '@/utils/auth'
import { Notification } from 'element-ui'
export function formatter (number) {
  const numbers = number.toString().split('').reverse()
  const segs = []

  while (numbers.length) segs.push(numbers.splice(0, 3).join(''))

  return segs.join(',').split('').reverse().join('')
}

/**
 * 10000 => '10,000"
 * @param {number} num
 */
export function toThousandFilter (num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

// ['2020-01', '2020-02']
export function getBeforeMonth (num) {
  const dataArr = []
  const data = new Date()
  data.setMonth(data.getMonth(), 1)
  for (let i = 0; i < num; i++) {
    data.setMonth(data.getMonth() - 1)
    let m = data.getMonth() + 1
    m = m < 10 ? '0' + m : m
    dataArr.push(data.getFullYear() + '-' + (m))
  }
  dataArr.reverse()
  return dataArr
}

// ['1月', '2月']
export function getBeforeMonthStr (num, space) {
  const dataArr = []
  const data = new Date()
  data.setMonth(data.getMonth(), 1)
  for (let i = 0; i < num; i++) {
    data.setMonth(data.getMonth() - 1)
    const m = data.getMonth() + 1
    const str = space ? m + ' 月' : m + '月'
    dataArr.push(str)
  }
  dataArr.reverse()
  return dataArr
}

// 1月到12月
export function getCurrentMonthArr (num, space) {
  const dataArr = []
  for (let m = 0; m < num; m++) {
    const str = space ? (m + 1) + ' 月' : (m + 1) + '月'
    dataArr.push(str)
  }
  return dataArr
}

export function getUrlParam (paraName) {
  var url = document.location.toString()
  var arrObj = url.split('?')

  if (arrObj.length > 1) {
    var arrPara = arrObj[1].split('&')
    var arr

    for (var i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')

      if (arr != null && arr[0] == paraName) {
        return arr[1]
      }
    }
    return ''
  } else {
    return ''
  }
}

// export function getTokenAPI (cb) {
//   const code = getUrlParam('code')
//   const params = {
//     code: code
//   }
//   console.log('cb', 'code', code, cb)
//   getAuthorize(params).then(res => {
//     if (res.code === 0) {
//       setToken(res.data.result.access_token)
//       if (cb) cb()
//     } else {
//       Notification.error({
//         title: '消息提示',
//         message: res.message || '获取token失败',
//         position: 'bottom-left'
//       })
//     }
//   }).catch(() => {
//     Notification.error({
//       title: '消息提示',
//       message: '获取token失败',
//       position: 'bottom-left'
//     })
//   })
// }

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if (!time) return ''
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  var changeTime
  if (typeof time === 'object') {
    changeTime = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    changeTime = new Date(time.replace(/-/g, '/'))
  }
  const formatObj = {
    y: changeTime.getFullYear(),
    m: changeTime.getMonth() + 1,
    d: changeTime.getDate(),
    h: changeTime.getHours(),
    i: changeTime.getMinutes(),
    s: changeTime.getSeconds(),
    a: changeTime.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, function (result, key) {
    var value = formatObj[key]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

// 后端返回的价格单位都是分，前端需要一个分转元的函数,如果是负数则加-
export function priceFormat(limitPrice = 0, upperPrice = 0) {
  limitPrice = limitPrice || 0;
  upperPrice = upperPrice || 0;

  if (limitPrice === 0 && upperPrice === 0) {
    return 0;
  }

  if (limitPrice === 0) {
    return priceToThousands(upperPrice);
  }

  if (upperPrice === 0) {
    return priceToThousands(limitPrice);
  }
  return limitPrice == upperPrice ? priceToThousands(limitPrice) : `${priceToThousands(limitPrice)}~${priceToThousands(upperPrice)}`
}

export function regFenToYuan(fen) {
  let num = fen;
  num = fen * 0.01;
  num += '';
  let reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
  num = num.replace(reg, '$1');
  num = toDecimal2(num)
  return num
};

// 保留两位小数
function toDecimal2(x) {
  let f = parseFloat(x);
  if (isNaN(f)) {
      return '--';
  }
  f = Math.round(x * 100) / 100;
  if (Number.isInteger(f)) {
    return f.toString();
  }
  let s = f.toString();
  let rs = s.indexOf('.');
  if (rs < 0) {
      rs = s.length;
      s += '.';
  }
  while (s.length <= rs + 2) {
      s += '0';
  }
  return s;
}

// 格式化金钱，三位加一个逗号
export function priceToThousands(num) {
  if (num) {
      num = regFenToYuan(num)
      //将num中的$,去掉，将num变成一个纯粹的数据格式字符串
      num = num.toString().replace(/\$|\,/g, '');
      //如果num不是数字，则将num置0，并返回
      if ('' == num || isNaN(num)) {
          return 'Not a Number ! ';
      }
      //如果num是负数，则获取她的符号
      var sign = num.indexOf("-") > 0 ? '-' : '';
      //如果存在小数点，则获取数字的小数部分
      var cents = num.indexOf(".") > 0 ? num.substr(num.indexOf(".")) : '';
      cents = cents.length > 1 ? cents : '';//注意：这里如果是使用change方法不断的调用，小数是输入不了的
      //获取数字的整数数部分
      num = num.indexOf(".") > 0 ? num.substring(0, (num.indexOf("."))) : num;
      //如果没有小数点，整数部分不能以0开头
      if ('' == cents) {
          if (num.length > 1 && '0' == num.substr(0, 1)) {
              return 'Not a Number ! ';
          }
      }
      else {
          if (num.length > 1 && '0' == num.substr(0, 1)) {
              return 'Not a Number ! ';
          }
      }
      for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
          num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
      }
      return (sign + num + cents);
  } else if (num === 0) {
      return '0'

  }
  else {
      return '--'
  }
}

// 判断数字是否连续
export function isCountNum(num = '') {
  if (num.includes(',')) {
   num = num.replaceAll(',', '')
  }
  let ncontinuity=0;
  for(let i=1;i<num.length;i++){
    if((num[i]-num[i-1]==1)||(num[i]-num[i-1]==-1)){
      ncontinuity+=1;
    };
  }
  return ncontinuity > (num.length-2)
}
// 转义工作时间
export function workDate(workDate = '') {
  let obj = {
      1: '一',
      2: '二',
      3: '三',
      4: '四',
      5: '五',
      6: '六',
      7: '日'
  }
  return isCountNum(workDate) ? `周${obj[workDate.split(',')[0]]}至周${obj[workDate.split(',').pop()]}` : workDate.split(',').map(i => '周' + obj[i]).toString();
}
